var gConverterToPostList = Cc["@mozilla.org/streamconv;1?from=application/onthewave.postlist&to=*/*"].getService().wrappedJSObject;
var tabulator = Cc["@dig.csail.mit.edu/tabulator;1"].getService().
                wrappedJSObject;
var gIOService = Cc["@mozilla.org/network/io-service;1"].
                 getService(Ci.nsIIOService);
var gBBSProtocol = Components.classes["@mozilla.org/network/protocol;1?name=bbs"].getService().wrappedJSObject;
String.prototype.startswith = function startswith(aOther){
  return this.substr(0, aOther.length) === aOther;
}

FeedHandler.buildFeedList = function(e){ 
  document.getElementById("feed-button").setAttribute("feed", "");
  return false;
}
FeedHandler.onFeedButtonClick = function onthewaveFeedButtonOverride(e){
  e.stopPropagation();
  if (e.target.hasAttribute("feed") &&
      e.eventPhase == Event.AT_TARGET &&
      (e.button == 0 || e.button == 1)) {
    var sf = tabulator.sf;
    var kb = tabulator.kb;
    function SIOC(aTerm) kb.sym("http://rdfs.org/sioc/ns#" + aTerm);

    // 2 cases: SIOC and RSS/Atom Feed

    // case 1: SIOC

    var theBrowser = gBrowser.selectedBrowser;
    if (theBrowser.sioc){ //@more than one SIOC
      // The URI to be displayed with post_list.html should be a Forum URI,
      // but the exact URI is not yet known before SIOC metadata is 
      // fetched. Make the throbbers run now.
      var i;      
      for (i = 0; i < gBrowser.browsers.length; i++)
        if (theBrowser === gBrowser.browsers[i]) break;
      var listener = gBrowser.mTabListeners[i];
      var fakeChannel = gIOService.newChannel(gBrowser.currentURI.spec, 
                                              null, null);
      // this channel is not opened, it is passed to onChange as a dummy.
      
      listener.onStateChange(theBrowser.webProgress, fakeChannel,
                             Ci.nsIWebProgressListener.STATE_START | 
                             Ci.nsIWebProgressListener.STATE_IS_NETWORK, 
                             0);
      
      function loadForum(uri){
        if (uri !== theBrowser.sioc) return true;
        // Stop the throbbers
        
        listener.onStateChange(theBrowser.webProgress, fakeChannel,
                               Ci.nsIWebProgressListener.STATE_STOP | 
                               Ci.nsIWebProgressListener.STATE_IS_NETWORK, 
                               0);
        

        var uri = theBrowser.currentURI.spec;
        var hashLoc = uri.indexOf("#");
        var docURI = (hashLoc === -1)? uri: uri.substr(0, hashLoc);
        // strip out the #, we don't have to be this strict on asking
        // the URI to be exactly corrected. We are opening the SIOC:Forum
        // not the SIOC:Site anyway.
        var forum = kb.any(kb.sym(docURI), SIOC('host_of'));
        if (forum){
          // http://www.wretch -> bbs://www.wretch (為了觸發onthewave)
          var uriToRead = "bbs" + forum.uri.substr(4, forum.uri.length);
          gConverterToPostList.convertResource(forum.uri);
          //gBrowser.addTab(forum.uri);
          theBrowser.contentWindow.location.assign(forum.uri);
        } else {
          alert("Although SIOC data is detected on this page, there is no forum or blog to be opened with onthewave");
        }
        return false;
       
      }
      // register call back before looking up the thing, becuase
      // lookUpThing might not do asynchrous fetching (say, when the
      // thing is cached)
      sf.addCallback('done', loadForum);
      sf.lookUpThing(kb.sym(theBrowser.sioc));
      return;
    }
    // case 2: 
    // load all the feed information into kb
    gFeeds = gBrowser.selectedBrowser.feeds.map(function(x) x.href);
    for (var i = 0; i < gFeeds.length; i++){
      dump("fetching " + gFeeds[i] + "\n");
      sf.lookUpThing(kb.sym(gFeeds[i]));
    }
    // reload the resource again with overridden content type
    // http://www.wretch -> bbs://www.wretch (為了觸發onthewave)
    var currentURI = gBrowser.currentURI.spec;
    var uriToRead = "bbs" + currentURI.substr(4, currentURI.length);
    gBBSProtocol.tweakUriBack(uriToRead, false);
    theBrowser.contentWindow.location.assign(uriToRead);
    //gConverterToPostList.convertResource(gBrowser.currentURI.spec);
    //BrowserReloadSkipCache();

  }
};

/*
function passingGlobals(event){
  if (event.originalTarget.location &&
      event.originalTarget.location.href == 
      gConverterToPostList._uriToConvert){
    gConverterToPostList._uriToConvert = "";
    content.wrappedJSObject.tabulator = tabulator;
    content.wrappedJSObject.gConverterToPostList = gConverterToPostList;
    //content.wrappedJSObject.feeds = gFeeds;
    //gFeeds = null;
    content.focus();
  }
}
*/

//This follows convention used in WP SIOC Plugin
const SIOCSniffer = { //@look into the spec or how Semantic Rador does
  handleEvent: function SIOCSniffer(event) {
    if (event.type !== "DOMLinkAdded") return;
    var link = event.originalTarget;
    if (link.title === "SIOC"){
      var browser = gBrowser.getBrowserForDocument(link.ownerDocument);
      browser.sioc = link.href;
    }
  }
};

//gBrowser.addEventListener('DOMContentLoaded', passingGlobals, true);
//'DOMContentLoaded' goes faster then 'load'
gBrowser.addEventListener("DOMLinkAdded", SIOCSniffer, false);
